package com.fenye.testflow.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fenye.testflow.mapper.SysRoleMapper;
import com.fenye.testflow.mapper.SysUserMapper;
import com.fenye.testflow.mapper.SysUserRoleMapper;
import com.fenye.testflow.model.common.GuiguException;
import com.fenye.testflow.model.common.ResultCodeEnum;
import com.fenye.testflow.model.dto.LoginDto;
import com.fenye.testflow.model.entity.system.SysRole;
import com.fenye.testflow.model.entity.system.SysUser;
import com.fenye.testflow.model.entity.system.SysUserRole;
import com.fenye.testflow.model.vo.LoginVo;
import com.fenye.testflow.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysSUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private RedisTemplate <String,String> redisTemplate;
    @Override
    public LoginVo login(@RequestBody LoginDto loginDto) {
        // 校验验证码是否正确
        String captcha = loginDto.getCaptcha();     // 用户输入的验证码
        String codeKey = loginDto.getCodeKey();     // redis中验证码的数据key
        String redisCode = redisTemplate.opsForValue().get("user:login:validatecode:" + codeKey);
        if(StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode , captcha)) {
            System.out.println("redisCode=="+redisCode);
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR) ;
        }
        // 验证通过删除redis中的验证码
        redisTemplate.delete("user:login:validatecode:" + codeKey) ;

        //查询名称查询用户
        SysUser sysUser = sysUserMapper.selectByName(loginDto.getUsername());

        //判断密码是否对
        String password = loginDto.getPassword();
//        String md5InputPassword = DigestUtils.md5DigestAsHex(password.getBytes());
//        if (!md5InputPassword.equals(sysUser.getPassword())) {
//            throw new RuntimeException("用户名或密码错误");
//        }

        if (!password.equals(sysUser.getPassword())){
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
        //生成随机令牌，存储到redis中
        String token = UUID.randomUUID().toString().replace("_", "");
        redisTemplate.opsForValue().set("user:login:"+token, JSON.toJSONString(sysUser),20, TimeUnit.MINUTES);

        //构造响应结果
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");

        //返回
        return  loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        return JSON.parseObject(userJson,SysUser.class);
    }

    @Override
    public Boolean saveUserRole(SysUserRole sysUserRole) {
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, sysUserRole.getUserId());
        sysUserRoleMapper.delete(queryWrapper);
        int insertNum = sysUserRoleMapper.insert(sysUserRole);
        return (insertNum > 0) ? true : false;
    }

    @Override
    public List<SysUser> getUserForRoleList(String roleCode) {
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRole::getRoleCode, roleCode);
        System.out.println("roleCode=="+roleCode);
        Long roleId = sysRoleMapper.selectOne(queryWrapper).getId();
       List<Long> userIdList =  sysUserRoleMapper.getUserIdsByRoleId(roleId);
       return this.listByIds(userIdList);
    }
}
